# _*_ encoding:utf-8 _*_

from rest_framework import serializers

from goods.models import SKU, SPUSpecification, SKUSpecification, GoodsCategory, SPU, SpecificationOption


class SPUSpecOptionModelSerializer(serializers.ModelSerializer):
    """SPU商品规格选项"""

    class Meta:
        model = SpecificationOption
        fields = ['id', 'value']


class SPUSpecModelSerializer(serializers.ModelSerializer):
    """SPU商品规格模型类序列化器"""
    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()
    options = SPUSpecOptionModelSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = ['id', 'name', 'spu', 'spu_id', 'options']


class SPUSimpleModelSerializer(serializers.ModelSerializer):
    """SPU模型类序列化器"""

    class Meta:
        model = SPU
        fields = ['id', 'name']


class GoodsCategryModelSerializer(serializers.ModelSerializer):
    """分类模型类序列化器"""

    class Meta:
        model = GoodsCategory
        fields = ['id', 'name']


class SKUSpecOptModelSerializer(serializers.ModelSerializer):
    """SKU规格模型类序列化器"""
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ['spec_id', 'option_id']


class SKUSimpleModelSerializer(serializers.ModelSerializer):
    """获取简单SKU模型类序列化器"""

    class Meta:
        model = SKU
        fields = ['id', 'name']


class SKUModelSerializer(serializers.ModelSerializer):
    """SKU模型类序列化器"""

    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()
    category = serializers.StringRelatedField()
    category_id = serializers.IntegerField()

    specs = SKUSpecOptModelSerializer(many=True)

    class Meta:
        model = SKU
        fields = "__all__"

    def create(self, validated_data):
        specs = validated_data.pop('specs')

        sku = super().create(validated_data)

        for spec in specs:
            spec['sku_id'] = sku.id
            SKUSpecification.objects.create(**spec)

        return sku

    def update(self, instance, validated_data):
        specs = validated_data.pop('specs')

        sku = super().update(instance, validated_data)

        SKUSpecification.objects.filter(sku=sku).delete()

        for spec in specs:
            spec['sku_id'] = sku.id
            SKUSpecification.objects.create(**spec)

        return sku

